package com.javabasic.tool;

/**
 * @Author xiongmin
 * @Description TODO
 * @Date 2019/10/29 17:05
 * @Version 1.0
 **/
public class TestIp {

    public static boolean isInRange(String network, String mask) {
        String[] networkips = network.split("\\.");
        int ipAddr = (Integer.parseInt(networkips[0]) << 24)
                | (Integer.parseInt(networkips[1]) << 16)
                | (Integer.parseInt(networkips[2]) << 8)
                | Integer.parseInt(networkips[3]);
        int type = Integer.parseInt(mask.replaceAll(".*/", ""));
        int mask1 = 0xFFFFFFFF << (32 - type);
        String maskIp = mask.replaceAll("/.*", "");
        String[] maskIps = maskIp.split("\\.");
        int cidrIpAddr = (Integer.parseInt(maskIps[0]) << 24)
                | (Integer.parseInt(maskIps[1]) << 16)
                | (Integer.parseInt(maskIps[2]) << 8)
                | Integer.parseInt(maskIps[3]);

        return (ipAddr & mask1) == (cidrIpAddr & mask1);
    }

    public static void main(String[] args) {
        System.out.println(isInRange("10.153.48.127", "10.153.48.0/26"));
        System.out.println(isInRange("10.168.1.2", "10.168.0.224/23"));
        System.out.println(isInRange("192.168.0.1", "192.168.0.0/24"));
        System.out.println(isInRange("10.168.0.0", "10.168.0.0/32"));
        System.out.println(isInRange("192.168.24.205", "192.168.24.195/26"));


        validateCidrIP(" 10.25.155.0/23");
        validateCidrIP(" 10.25.155.0/24");
    }

    public static boolean validateCidrIP(String cidrIP) {
        if (!cidrIP.contains("/")) {
            return true;
        }
        String[] split = cidrIP.trim().split("/");
        Long aLong = ipToNumber(split[0]);
        long temp = 1L;
        temp = (temp << Integer.parseInt(split[1])) - 1;
        temp = (temp << (32-Integer.parseInt(split[1])));

        System.out.println("temp = " + Long.toBinaryString(temp));
        System.out.println("aLong = " + Long.toBinaryString(aLong));

        if ((temp & aLong) == aLong)  {
            System.out.println("YES");
            return true;
        } else {
            System.out.println("NO");
            return false;
        }
    }

    private static Long ipToNumber(String ip) {
        Long ips = 0L;
        String[] numbers = ip.split("\\.");
        //等价上面
        for (int i = 0; i < 4; ++i) {
            ips = ips << 8 | Integer.parseInt(numbers[i]);
        }
        return ips;
    }

    private static String numberToIp(Long number) {
        //等价上面
        String ip = "";
        for (int i = 3; i >= 0; i--) {
            ip  += String.valueOf((number & 0xff));
            if(i != 0){
                ip += ".";
            }
            number = number >> 8;
        }

        return ip;
    }
}